#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
	int pipedes[2];
	if (pipe(pipedes)) {
		printf("创建管道失败\n");
		return -1;
	}
	pid_t pid = fork();
	printf("%d start\n", getpid());
	char buffer[1024];
	if (pid == 0) {
		close(pipedes[1]);
		int read_size = 0;
		while ((read_size = read(pipedes[0], buffer, 1024)) > 0) {
			write(STDOUT_FILENO, buffer, read_size);
		}
		printf("子进程退出\n");
		_exit(EXIT_SUCCESS);
	} else if (pid > 0) {
		close(pipedes[0]);
		int n = 0;
		sleep(1);
		for (int i = 0; i < 4; ++i) {
			n = sprintf(buffer, "i = %d\n", i);
			write(pipedes[1], buffer, n);
		}
		close(pipedes[1]);
		waitpid(pid, NULL, 0);
		printf("主进程退出\n");
		exit(EXIT_SUCCESS);
	} else if (pid == -1) {
		printf("创建进程失败\n");
		return -1;
	} else {
		printf("未知\n");
		return -1;
	}
	return 0;
}